<?php
/**
 * 订单控制器
 * 短信通知、微信通知等通知方式
 *
 * @package  app
 * @extends  Controller
 */
class Controller_Order extends Controller_BaseController {

    public $template = 'template';

    public function before(){
        parent::before();
    }

    /**
    * 创建订单，并且根据支付类型，转
    * 入支付页面
    */
    public function action_create(){

        if(\Input::method() == 'POST'){

            //获取数据
            $seller = \Session::get('seller', false);
            $account = \Session::get('WXAccount', false);
            $data = \Input::post();

            $order = \Model_Order::forge($data);
            //订单数据
            $order->order_no = time();
            $order->user_id = \Auth::get_user()->id;
            $order->from_id = $seller->user_id;         

            //通过cookie获取订单明细
            $order->details = array();

            //初始化交易对象
            $trade = array(
                'return_status' => 'NONE',
                'real_money' => $data['money'], 
                'notify_status' => 'NONE'
            );
            $order->trade = \Model_OrderTrade::forge($trade);

            if( ! $order->save()){
                if(\Input::is_ajax()){
                    die(json_encode(array('status' => 'err', 'msg' => '订单创建失败', 'errcode' => 20)));
                }
                die('订单创建失败');
            }

            //清除cookie中的订单数据

            //通知用户下单成功
            if(\Session::get('seller')->user_alert_status){
                $alerts = explode(',', \Session::get('seller')->user_alerts);
                foreach ($alerts as $key => $value) {
                    if($value == 'email'){
                        //发送邮件
                    }else if($value == 'sms'){
                        //发送短信
                    }else if($value == 'wechat'){
                        //发送微信
                    }
                }
            }

            //通知商户有商户下单
            if(\Session::get('seller')->seller_alert_status){
                $alerts = explode(',', \Session::get('seller')->seller_alerts);
                foreach ($alerts as $key => $value) {
                    if($value == 'email'){
                        //发送邮件
                        $data = array();
                        $this->notice_email($data, explode(',', \Session::get('seller')->seller_alert_email));
                    }else if($value == 'sms'){
                        //发送短信
                        $data = array();
                        $this->notice_sms($data, explode(',', \Session::get('seller')->seller_alert_wechat));
                    }else if($value == 'wechat'){
                        //发送微信
                        $data = array();
                        $this->notice_wechat($data, explode(',', \Session::get('seller')->seller_alert_wechat));
                    }
                }
            }

            //转入订单支付页
            if($order->payment_type == 'alipay'){

            }else if($order->payment_type == 'tenpay'){

            }else if($order->payment_type == 'wxpay'){

            }else if($order->payment_type == 'offline'){

            }

            $result = \Model_Order::do_create($data);
            if($result['ret'] == 'succ'){
                \Cookie::delete('book_address_info');
                //订单创建提醒
                if(! empty($seller->alert)){

                    if(strpos($seller->alert, 'email') !== false){

                    }

                    if(strpos($seller->alert, 'sms') !== false){

                    }

                    if(strpos($seller->alert, 'wechat') !== false){
                        $account = \Model_WXAccount::find(1);
                        if(time() > $account->temp_token_valid){
                            $ret = \Tools::send("/app/token/{$account->id}");
                            $ret = json_decode($ret);
                            if($ret->status == 'err'){
                                \Log::error("获取token异常，信息：{$ret} in " . __FILE__);
                            }                           
                            $account->temp_token = $ret->data;
                        }

                        if( isset($seller->alert_wechat) && ! empty($seller->alert_wechat)){
                            foreach (explode(',', $seller->alert_wechat) as $key => $value) {
                                if(empty($value)){
                                    continue;
                                }
                                $wxuser = \Model_WXUser::find($value);
                                //读通知商户，读通知模板
                                /*$params = array(
                                    'to_user' => $wxuser->openid,
                                    'msg_type' => 'text',
                                    'content' => "尊敬的【{$seller->name}】，您有一笔未处理的订单。订单编号：{$result['data']->order_no}",
                                );
                                $ret = \Tools::send("/app/wx_send/text/{$account->temp_token}", 'POST', $params);
                                if(json_decode(json_decode($ret->body)->body)->errcode > 0){
                                    \Log::error("微信通知异常信息(seller:{$seller->user_id}【{$seller->name}】)：" . json_decode($ret->body)->body);
                                }*/

                                //通知模板数据填充
                                $details = '';
                                foreach ($result['data']->details as $detail) {
                                    $details .= $detail->goods->node->title . "(" . $detail->goods->node->category->name . "),";
                                }

                                $notice = \Model_WXAccountNotice::getItem(array('account_id' => $account->id, 'template_id' => 2));

                                $params = array(
                                    'touser' => $wxuser->openid,
                                    'template_id' => $notice->tpl_id,
                                    'url' => \Config::get('base_url') . "/order/view/{$result['data']->id}",
                                    'topcolor' => '#428bca',
                                    'data' => array(
                                        "first" => array(
                                            'value' => '尊敬的易微信商家：您有一个新订单请及时处理！',
                                            'color' => '#428bca'
                                        ),
                                        "tradeDateTime" => array(
                                            "value" => date('Y-m-d H:i', $result['data']->created_at),
                                            "color" => "#000"
                                        ),
                                        "orderType" => array(
                                            "value" => \Model_Order::$_maps['type'][$result['data']->order_type],
                                            "color" => "#000"
                                        ),
                                        "customerInfo" => array(
                                            "value" => "{$result['data']->name}\n客户电话：{$result['data']->phone}\n客户地址：{$result['data']->address}",
                                            "color" => "#000"
                                        ),
                                        "orderItemName" => array(
                                            "value" => $result['data']->order_type == 'TAKEAWAY' ? "预订菜品" : '预订目录',
                                            "color" => "#000"
                                        ),
                                        "orderItemData" => array(
                                            "value" => $details,
                                            "color" => "#000"
                                        ),
                                        "remark" => array(
                                            "value" => "送达时间：" . (empty($result['data']->arrived_at) ? '尽快送达' : date('Y-m-d H:i', $result['data']->arrived_at)) . "\n订单编号：{$result['data']->order_no}",
                                            "color" => "#000"
                                        )
                                    )
                                );
                                $ret = \Tools::send("/app/tpl_msg/{$account->temp_token}", 'POST', $params);
                            }
                        }
                    }
                }

                $order = $result['data'];
                if(\Input::is_ajax()){
                    die(json_encode(array('status' => 'succ', 'msg' => '保存成功', 'data' => json_encode($result['data']->to_array()))));
                }else{
                    $module = \Session::get('module');
                    if(isset($data['to_url'])){
                        \Response::redirect("{$data['to_url']}/{$order->id}");
                    }else if(isset($data['payment_type']) && $data['payment_type'] == 'alipay'){
                        //获取卖家的支付宝信息
                        \Response::redirect("/trade/alipay_wap/request.php?out_trade_no={$order['order_no']}&subject=购买&total_fee={$order['original_money']}");
                    }else if(isset($data['payment_type']) && $data['payment_type'] == 'offline'){
                        //获取卖家的支付宝信息
                        \Response::redirect("/{$module}/order/callback/{$order->order_no}");
                    }else{
                        \Response::redirect("/{$module}/order/view/{$order->id}");
                    }
                    
                }
            }
        }
    }

    /**
    * email通知方法
    */
    protected function notice_email($data = array(), $emails = array()){
        foreach ($accounts as $key => $value) {
            $email = \Email::forge('notices');
            $email->from("notice@evxin.com", "易微信事件通知中心");
            $email->to($emails);
            $email->html_body(\View::forge("html/order/default", $data));
            $email->alt_body("订单通知");

            try{
                $email->send();
            }catch(\EmailValidationFailedException $e){
                \Log::error("发送通知邮件失败EmailValidationFailedException：" . $e->getMessage());
            }catch(\EmailSendingFailedException $e){
                \Log::error("发送通知邮件失败EmailSendingFailedException：" . $e->getMessage());
            }
        }
    }

    /**
    * 短信通知方法
    */
    protected function notice_sms(){

    }

    /**
    * 微信通知方法
    */
    protected function notice_wechat(){

    }
}